//
//  HMHTTPClient.swift
//  SecondWB
//
//  Created by 赖建伟 on 16/11/27.
//  Copyright © 2016年 Itheima. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPType: String {
    case post = "POST"
    case get = "GET"
    case head = "HEAD"
}

class HMHTTPClient: AFHTTPSessionManager {
    
    static let shareInstance:HMHTTPClient = {
       
        let baseURL = URL.init(string: "http//api.weibo.com/")
        
        let afn = HMHTTPClient(baseURL: baseURL)
        
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return afn
        
    }()
    
//    override func get(_ URLString: String, parameters: Any?, progress downloadProgress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)? = nil) -> URLSessionDataTask? {}
    ///把post和get封装成一个方法
    func request(type:HTTPType,longUrlString: String, parameters: Any?, progress downloadProgress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)? = nil) {
        
        if type == .get {
            
            self.get(longUrlString, parameters: parameters, progress: downloadProgress, success: success, failure: failure)
            
        }else {
            
            self.post(longUrlString, parameters: parameters, progress: downloadProgress, success: success, failure: failure)
        }
        
    }
    
    func request(type:HTTPType,urlString: String, parameters: Any?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)? = nil) {
        self.request(type: type, longUrlString: urlString, parameters: parameters, progress: nil, success: success, failure: failure)
    }
    ///舍去参数后的请求方法
    func request(type:HTTPType,shortUrlString: String, parameters: Any?, success:(([String:Any])->Void)?, failure: ((Error) -> Void)? = nil) {
        
        let successClosure = {(task:URLSessionDataTask,josn: Any?) -> Void in
            if let josn = josn as? [String:Any] {
               success?(josn)
            }
            
        }
        
        let failureClosure = {(task:URLSessionDataTask?,error: Error) -> Void in
            
            failure?(error)
            
        }
        
        self.request(type: type, urlString:shortUrlString, parameters: parameters, success: successClosure, failure: failureClosure)
        
    }
    ///类方法请求数据
    class func request(type:HTTPType,classUrlString: String, parameters: Any?, success:(([String:Any])->Void)?, failure: ((Error) -> Void)? = nil)  {
        
        HMHTTPClient.shareInstance.request(type: type, shortUrlString: classUrlString, parameters: parameters, success: success, failure: failure)
        
        
    }
    
    
}
